package com.example.damaicache.web;

import com.example.damaicache.web.fegin.OtherAction;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/7/12
 * Email haijunzhou@hnit.edu.cn
 */
@RestController
public class CacheDo {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    OtherAction otherAction;

    @RequestMapping("queryByIndex")
    public Map<String,Object> queryByIndex() throws JsonProcessingException {
        Map<String,Object> ret = null;
        ValueOperations value = redisTemplate.opsForValue();
        ObjectMapper mapper = new ObjectMapper();
        if(redisTemplate.hasKey("cache-queryByIndex")){
            // 首先从 redis 查询数据
            String json = (String) value.get("cache-queryByIndex");
            ret = mapper.readValue(json, HashMap.class);
        } else {
            // 如果没有则从远程查询
            ret = otherAction.queryByIndex();
            // 再缓存到 redis 中
            String json = mapper.writeValueAsString(ret);
            value.set("cache-queryByIndex", json);
        }
        return ret;
    }

    public void queryCategory(){
        System.out.println("========= queryCategory =========");
    }

    public void A(){
        System.out.println("========= A =========");
    }

    public void B(){
        System.out.println("========= B =========");
    }


    @Scheduled(cron = "0 0 0 * * ?")
    public void refresh() throws InvocationTargetException, IllegalAccessException {
        // 清理 redis 中缓存的数据
        Set keys = redisTemplate.keys("cache-*");
        for (Object key : keys) {
            System.out.println("清除缓存数据: " + key);
            redisTemplate.delete(key);
        }

        Method[] methods = this.getClass().getDeclaredMethods();
        for (Method method : methods) {
            if(method.getName().equals("refresh")
                    || method.getName().equals("init")){
                continue;
            }
            method.invoke(this);
        }
    }

    // spring 在创建对象之后, 注入完所有的bean
    @PostConstruct
    public void init() throws InvocationTargetException, IllegalAccessException {
        refresh();
    }


}
